<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\WorkTemplate;
use app\admin\model\WorkTemplateItem;
use app\admin\model\AdminNotice;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use think\Session;
use think\Db;
/**
 * 浮动性工作模板提交管理
 *
 * @icon fa fa-circle-o
 */
class WorkTemplateExamineLog extends Backend
{

    public $group;
    /**
     * WorkTemplateLog模型对象
     * @var \app\admin\model\WorkTemplateLog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorkTemplateLog;
        $this->view->assign("type_arr", (new WorkTemplate())->type_arr);

        
        $this->assign('group',$this->admin_group);
        $this->group = $this->admin_group;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $and_where = [];
            $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
            if(empty($AuthGroupAccessInfo))$this->error('登录错误');
            if($AuthGroupAccessInfo['group_id'] == 10){
                $admin_ids = $this->_get_admin_ids();
                $and_where['admin_id'] = ['in',$admin_ids];
            }
            $group_info = $this->group;
            $list = $this->model
                ->with(['admin','template'])
                ->where(function($query) use ($group_info,$limit){
                    if(!in_array($group_info['id'],[1,6,8])){
                        if($group_info['check_auth'] == 1){
                            $query->whereIn('work_template_log.status',[
                                2,3,4,5,6
                            ]);

                        }else if($group_info['check_auth'] == 2){
                            $query->whereIn('work_template_log.status',[
                                3,5,6
                            ]);
                        }else{
                            $query->where('work_template_log.admin_id',-1);
                        }
                    }
                    if($limit == 999999){
                        $query->where('work_template_log.status',5);
                    }
                })
                ->where('work_template_log.status',">",1)
                ->where($where)
                ->where($and_where)
                ->orderRaw('field(work_template_log.status,2,3,5,4,6)')
//                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $first_trial_admin = Admin::where('id',$row->first_trial_admin_id)->field('nickname,signature')->find();
                $row->first_trial_admin_name = $first_trial_admin?$first_trial_admin['nickname']:'';
                $row->first_trial_admin_signature = $first_trial_admin?$first_trial_admin['signature']:'';

                $end_trial_admin = Admin::where('id',$row->end_trial_admin_id)->field('nickname,signature')->find();
                $row->end_trial_admin_name = $end_trial_admin?$end_trial_admin['nickname']:'';
                $row->end_trial_admin_signature = $end_trial_admin?$end_trial_admin['signature']:'';

                $row->check_auth = $this->admin_check_auth;

                $row->visible(['id','admin_id','type','teacher_type','select_time','status','reject_reason',
                    'first_trial_reject_reason','first_trial_admin_name','first_trial_time',
                    'end_trial_reject_reason','end_trial_time','end_trial_admin_name','end_trial_admin_signature','first_trial_admin_signature','create_time','admin','template','check_auth']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 通过
     */
    public function pass_through($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                if($this->admin_check_auth == 1){ // 初审
                    // $work_template_info = WorkTemplate::where(['id'=>$row->temp_id])->find();
                    $temp_info = $this->model->where(['temp_id'=>$row->temp_id,'temp_item_id'=>$row->temp_item_id,'status'=>3])->find();
                    $nickname = Admin::where('id',$temp_info['admin_id'])->value('nickname');
                    if(!empty($temp_info))exception('此条数据与“'.$nickname.'”老师提交数据冲突，冲突数据ID为“'.$temp_info['id'].'”');
                    AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'1','content'=>'您提交的工作上报已初审通过'));
                    $res = $row->save(array('status'=>'3','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));

                }else if($this->admin_check_auth == 2){ // 终审
                    if($row->status != 3){
                        $this->error('当前状态无法操作');
                    }
                    $res = $row->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                    AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'3','content'=>'您提交的课时审核已终审通过'));

                }else{
                    $this->error('您没有审核权限');
                }

                if (!$res)exception('审核成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 驳回
     */
    public function reject($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if($this->admin_check_auth == 1){ // 初审
                        $params['status'] = '4';
                        $params['first_trial_admin_id'] = $this->auth->id;
                        $params['first_trial_time'] = date('Y-m-d H:i:s');
                        $result = $row->allowField(true)->save($params);
                        AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'2','content'=>'您提交的工作上报被初审驳回  驳回原因：'.$params['first_trial_reject_reason']));
                    }else if($this->admin_check_auth == 2){ // 终审
                        $params['status'] = '6';
                        $params['end_trial_admin_id'] = $this->auth->id;
                        $params['end_trial_time'] = date('Y-m-d H:i:s');
                        $result = $row->allowField(true)->save($params);
                        AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'4','content'=>'您提交的课时审核被终审驳回  驳回原因：'.$params['first_trial_reject_reason']));
                    }else{
                        $this->error('您没有审核权限');
                    }

                    if(!$result)exception('驳回失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 批量审核
     */
    public function batch_examine()
    {
        Db::startTrans();
        try {
            $idStr = $this->request->post('ids','');
            $type = $this->request->post('type','pass');
            $ids = json_decode($idStr,true);
            if(empty($ids))exception('请勾选您需操作的内容');

            if($type == 'pass'){
                foreach ($ids as $v){
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');

                    if($this->admin_check_auth == 1){ // 初审

                        if ($info['status'] != 2)exception('ID:'.$v.'的状态不正确，请先移除');
                        // $work_template_info = WorkTemplate::where(['id'=>$info->temp_id])->find();
                        $temp_info = $this->model->where(['temp_id'=>$info->temp_id,'temp_item_id'=>$info->temp_item_id,'status'=>3])->find();
                        $nickname = Admin::where('id',$temp_info['admin_id'])->value('nickname');
                        if(!empty($temp_info))exception('ID:'.$v.'</br>'.'此条数据与“'.$nickname.'”老师提交数据冲突，冲突数据ID为“'.$temp_info['id'].'”');
                        AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'1','content'=>'您提交的工作上报已初审通过'));
                        $res = $info->save(array('status'=>'3','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));

                    }else if($this->admin_check_auth == 2){ // 终审

                        if ($info['status'] != 3)exception('ID:'.$v.'的状态不正确，请先移除');

                        $res = $info->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                        AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'3','content'=>'您提交的课时审核已终审通过'));
                    }else{
                        $res = false;
                        exception('您的账号没有审核权限');
                    }

                    if (!$res)exception('ID:'.$v.'审核失败');
                }
            }else{
                foreach ($ids as $v) {
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if($this->admin_check_auth == 1){ // 初审

                        if ($info['status'] != 2)exception('ID:'.$v.'的状态不正确，请先移除');
                        $first_trial_reject_reason = '提交信息不完整';
                        $arr = array(
                            'status' => 4,
                            'first_trial_admin_id' => $this->auth->id,
                            'first_trial_time' => date('Y-m-d H:i:s'),
                            'first_trial_reject_reason' => $first_trial_reject_reason,
                        );
                        $res = $info->allowField(true)->save($arr);
                        AdminNotice::create(array('admin_id' => $info->admin_id, 'status' => '2', 'content' => '您提交的工作上报被初审驳回  驳回原因：' .$first_trial_reject_reason));

                    }else if($this->admin_check_auth == 2){ // 终审

                        if ($info['status'] != 3)exception('ID:'.$v.'的状态不正确，请先移除');
                        $end_trial_reject_reason = '提交信息不完整';

                        $arr = array(
                            'status' => 6,
                            'end_trial_admin_id' => $this->auth->id,
                            'end_trial_time' => date('Y-m-d H:i:s'),
                            'end_trial_reject_reason' => $end_trial_reject_reason,
                        );
                        $res = $info->allowField(true)->save($arr);
                        AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'4','content'=>'您提交的课时审核被终审驳回  驳回原因：'.$end_trial_reject_reason));
                    }else{
                        $res = false;
                        exception('您的账号没有审核权限');
                    }

                    if (!$res) exception('ID:'.$v.'驳回失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    public function _get_admin_ids()
    {
        $admin_list = Admin::where('business_administrator_id',$this->auth->id)->select();
        $admin_ids = array_column($admin_list,'id');
        return $admin_ids;
    }

}
